package com.springboot.myweb.config;


import com.springboot.myweb.service.UserService;
import com.springboot.myweb.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro认证中的详细用户权限分配
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录对象
        Subject subject = SecurityUtils.getSubject();
        //从认证中获取user对象
        User principal = (User) subject.getPrincipal();

        /*
         * 如果我们登录的是管理员给权限
         * 当然一般情况下数据库会有一个权限字段power
         *
         * */
        if( principal.getPower()==1){
            //添加权限
            info.addStringPermission("user:add");
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //取token
        UsernamePasswordToken usertoken =  (UsernamePasswordToken) authenticationToken;

        //连接真实数据库
        User users = userService.getUserByUsername(usertoken.getUsername());

        //这里只进行用户认证，因为密码认证被shiro接管
        if(users==null){
            return null;
        }

        //密码认证
        return new SimpleAuthenticationInfo(users,users.getPassword(),"");
    }
}
